import {createRouter, createWebHistory} from 'vue-router'
/* Layout */
import Layout from '@/layout'
import useUserStore from "@/store/modules/user.js";
import {ElMessage} from "element-plus";

// 公共路由
export const constantRoutes = [
    {
        path: '/redirect',
        component: Layout,
        hidden: true,
        children: [
            {
                path: '/redirect/:path(.*)',
                component: () => import('@/views/redirect/index.vue')
            }
        ]
    },
    {
        path: '/login',
        component: () => import('@/views/login'),
        hidden: true
    },
    {
        path: "/:pathMatch(.*)*",
        component: () => import('@/views/error/404'),
        hidden: true
    },
    {
        path: '/401',
        component: () => import('@/views/error/401'),
        hidden: true
    },
    {
        path: '/success',
        component: () => import('@/views/success/success'),
        hidden: true
    },
    {
        path: '/',
        component: () => import('@/components/MainLayout/index.vue'),
        children: [
            // 首页
            {
                path: '',
                component: () => import('@/views/index.vue'),
                meta: {
                    title: '首页',
                    requiresAuth: false,
                }
            },
            {
                // todo 测试 删除
                path: '/test',
                component: () => import('@/views/Test.vue'),
                hidden: true,
                meta: {
                    title: '测评完成页面',
                }
            },
            {
                path: 'online-assessments',
                component: () => import('@/views/assessments/assessments/perIndex.vue'),
                meta: {
                    title: '测评卷预览页面',
                    requiresAuth: true,
                }
            },
            {
                path: 'result',
                component: () => import('@/views/assessments/assessments/result.vue'),
                meta: {
                    title: '测评卷预览页面',
                    requiresAuth: true,
                }
            },
            {
                path: '/history',
                component: () => import('@/views/assessments/assessments/historyList.vue'),
                hidden: true,
                meta: {
                    title: '测评历史',
                    requiresAuth: true
                }
            },
            {
                path: '/compare-result',
                component: () => import('@/views/assessments/assessments/compareResult.vue'),
                hidden: true,
                meta: {
                    title: '历史对比',
                    requiresAuth: true
                }
            },
            {
                path: '/userInfo',
                component: () => import('@/views/system/user/profile/index'),
                name: 'userInfo',
                meta: {title: '个人中心', icon: 'user', requiresAuth: true}
            },
            {
                path: '/articlesList',
                component: () => import('@/views/articles/articlesList.vue'),
                name: 'articlesList',
                meta: {title: '文章列表', icon: 'user', requiresAuth: true}
            },
            {
                path: '/myArticles',
                component: () => import('@/views/articles/myArticles.vue'),
                name: 'myArticles',
                meta: {title: '我的文章', icon: 'user', requiresAuth: true}
            },
            {
                path: '/articleDetail',
                component: () => import('@/views/articles/articleDetail.vue'),
                name: 'articleDetail',
                meta: {title: '文章详情', icon: 'user', requiresAuth: true}
            },
            {
                path: '/applyFor',
                component: () => import('@/views/counselor/counselor/index'),
                name: 'applyFor',
                meta: {title: '成为咨询师', icon: 'user', requiresAuth: true}
            },
            {
                path: '/appointment',
                component: () => import('@/views/appointment/index.vue'),
                name: 'appointment',
                meta: {title: '在线预约', icon: 'user', requiresAuth: true}
            },
            {
                path: '/counselorDetails',
                component: () => import('@/views/appointment/appointmentDetails.vue'),
                name: 'counselorDetails',
                meta: {title: '预约详情页面', icon: 'user', requiresAuth: true}
            },
            {
                path: '/counselorSuccess',
                component: () => import('@/views/success/counselorSuccess.vue'),
                name: 'counselorSuccess',
                meta: {title: '预约成功页面', icon: 'user', requiresAuth: true}
            },
            {
                path: '/appointment-list',
                component: () => import('@/views/appointment/appointmentList.vue'),
                name: 'appointmentList',
                meta: {title: '我的预约', icon: 'user', requiresAuth: true}
            },
            {
                path: '/online-chat',
                component: () => import('@/views/websocket/websocket.vue'),
                name: 'onlineChat',
                meta: {title: '在线咨询', icon: 'user', requiresAuth: true}
            },
            {
                path: '/askAi',
                component: () => import('@/views/askAi/askAi.vue'),
                name: 'askAi',
                meta: {title: 'ai分析', icon: 'user', requiresAuth: true}
            },
            {
                path: '/noticeDetail',
                component: () => import('@/views/notice/noticeDetail.vue'),
                hidden: true,
                meta: {
                    title: '公告详情',
                    requiresAuth: true,
                }
            },
            {
                path: '/newsList',
                component: () => import('@/views/news/news/index.vue'),
                hidden: true,
                meta: {
                    title: '新闻列表',
                    requiresAuth: true,
                }
            },
            {
                path: '/newsDetail',
                component: () => import('@/views/news/news/newsDetail.vue'),
                hidden: true,
                meta: {
                    title: '新闻详情',
                    requiresAuth: true,
                }
            },

        ]
    },
    {
        path: '/examPage',
        component: () => import('@/views/assessments/assessments/index.vue'),
        hidden: true,
        meta: {
            title: '测评详情页面',
            requiresAuth: true,
        }
    },
    {
        path: '/success',
        component: () => import('@/views/success/success'),
        hidden: true,
        meta: {
            title: '测评完成页面',
            requiresAuth: true,
        }
    },



]

// 动态路由，基于用户权限动态去加载
export const dynamicRoutes = [
    {
        path: '/system/user-auth',
        component: Layout,
        hidden: true,
        permissions: ['system:user:edit'],
        children: [
            {
                path: 'role/:userId(\\d+)',
                component: () => import('@/views/system/user/authRole'),
                name: 'AuthRole',
                meta: {title: '分配角色', activeMenu: '/userManagement/role'}
            }
        ]
    },
    {
        path: '/system/role-auth',
        component: Layout,
        hidden: true,
        permissions: ['system:role:edit'],
        children: [
            {
                path: 'user/:roleId(\\d+)',
                component: () => import('@/views/system/role/authUser'),
                name: 'AuthUser',
                meta: {title: '分配用户', activeMenu: '/userManagement/user'}
            }
        ]
    },
    {
        path: '/system/dict-data',
        component: Layout,
        hidden: true,
        permissions: ['system:dict:list'],
        children: [
            {
                path: 'index/:dictId(\\d+)',
                component: () => import('@/views/system/dict/data'),
                name: 'Data',
                meta: {title: '字典数据', activeMenu: '/system/dict'}
            }
        ]
    },
    {
        path: '/monitor/job-log',
        component: Layout,
        hidden: true,
        permissions: ['monitor:job:list'],
        children: [
            {
                path: 'index/:jobId(\\d+)',
                component: () => import('@/views/monitor/job/log'),
                name: 'JobLog',
                meta: {title: '调度日志', activeMenu: '/monitor/job'}
            }
        ]
    },
    {
        path: '/tool/gen-edit',
        component: Layout,
        hidden: true,
        permissions: ['tool:gen:edit'],
        children: [
            {
                path: 'index/:tableId(\\d+)',
                component: () => import('@/views/tool/gen/editTable'),
                name: 'GenEdit',
                meta: {title: '修改生成配置', activeMenu: '/tool/gen'}
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes,
    scrollBehavior(to, from, savedPosition) {
        return savedPosition || {top: 0}
    }
})

// 路由守卫
router.beforeEach(async (to) => {
    const userStore = useUserStore()
    // 需要登录的页面
    if (to.meta.requiresAuth) {
        // 有 token 但未获取用户信息时
        if (userStore.token && !userStore.name) {
            try {
                await userStore.getInfo()
            } catch {
                return '/login'
            }
        }

        if (!userStore.token) {
            ElMessage.warning("请先登录！")
            return {
                path: '/login',
                query: {redirect: to.fullPath}
            }
        }
    }

    // 已登录访问登录页
    if (to.path === '/login' && userStore.token) {
        return {path: '/'}
    }
})

export default router;
